package org.auxgroup.smarthome;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;

/**
 * Created by kevinchen on 2017/8/3.
 * 定时任务管理类
 */
public class QuartzUtils {

    /**
     * 任务组
     */
    private final static String JOB_GROUP_NAME = "QUARTZ_JOBGROUP_NAME";
    /**
     * 触发器组
     */
    private final static String TRIGGER_GROUP_NAME = "QUARTZ_TRIGGERGROUP_NAME";
    /**
     * 创建一个SchedulerFactory工厂实例
     */
    private final static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    /**
     * 添加任务的方法
     * @param jobName  任务名
     * @param triggerName  触发器名
     * @param jobClass  执行任务的类
     * @param cronExpression  cron表达式
     */
    public static void addJob(String jobName,String triggerName,Class<? extends Job> jobClass,String cronExpression) throws SchedulerException{
        //LOG.info("==================initialization=================");
        //通过SchedulerFactory构建Scheduler对象
        Scheduler scheduler = schedulerFactory.getScheduler();
        //LOG.info("===================initialize finshed===================");
        //LOG.info("==============add the Job to Scheduler==================");
        //用于描叙Job实现类及其他的一些静态信息，构建一个作业实例
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(jobName, JOB_GROUP_NAME)
                .build();
        //构建一个触发器，规定触发的规则
        Trigger trigger = TriggerBuilder.newTrigger()//创建一个新的TriggerBuilder来规范一个触发器
                .withIdentity(triggerName, TRIGGER_GROUP_NAME)//给触发器起一个名字和组名
                .startNow()//立即执行
                .withSchedule(
                        CronScheduleBuilder.cronSchedule(cronExpression)
                                .withMisfireHandlingInstructionDoNothing()//不立即生效（激发该触发器）
                ).build();//产生触发器
        //向Scheduler中添加job任务和trigger触发器
        scheduler.scheduleJob(jobDetail, trigger);
        //启动
        scheduler.start();
    }

    /**
     * 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
     * @param triggerName
     * @param newCronExpression 新cron表达式
     */
    public static void modifyJobCronExpression(String triggerName, String newCronExpression) {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
            CronTriggerImpl cronTrigger = (CronTriggerImpl)scheduler.getTrigger(triggerKey);
            if(cronTrigger == null) {
                return;
            }
            String oldCronExpression = cronTrigger.getCronExpression();
            if (!oldCronExpression.equalsIgnoreCase(newCronExpression)) {
                cronTrigger.setCronExpression(newCronExpression);
                scheduler.rescheduleJob(triggerKey,cronTrigger);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 暂停触发器
     * @param triggerName
     */
    public static void pauseTrigger(String triggerName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
            scheduler.pauseTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 恢复触发器
     * @param triggerName
     */
    public static void resumeTrigger(String triggerName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, TRIGGER_GROUP_NAME);
            scheduler.resumeTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 暂停任务
     * @param jobName
     */
    public static void pauseJob(String jobName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 恢复任务
     * @param jobName
     */
    public static void resumerJob(String jobName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除任务
     * @param jobName
     */
    public static void deleteJob(String jobName){
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            if(!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}




